package org.wangp.gateway.sc.config

import cn.hutool.json.JSONUtil
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.wangp.framework.core.domain.CommonResult
import reactor.core.publisher.Mono
import java.nio.charset.Charset

/**
 * 已经的授权的用户 没有权限的处理
 * @author wangpeng (๑•ᴗ•๑)
 * @since 2021/10/7 1:16
 */
@Component
class RestfulAccessDeniedHandler : ServerAccessDeniedHandler {

	override fun handle(exchange: ServerWebExchange, denied: AccessDeniedException): Mono<Void> {
		val response = exchange.response
		response.statusCode = HttpStatus.OK
		response.headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
		val buffer = response.bufferFactory().wrap(
			JSONUtil.toJsonStr(
				CommonResult.fail(
					HttpStatus.FORBIDDEN.reasonPhrase,
					HttpStatus.FORBIDDEN.value()
				)
			).toByteArray(Charset.forName("UTF-8"))
		)
		return response.writeWith(Mono.just(buffer))
	}
}
